package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.domain.Floor;
import com.zzyl.nursing.domain.Room;
import com.zzyl.nursing.domain.RoomType;
import com.zzyl.nursing.mapper.RoomMapper;
import com.zzyl.nursing.service.IFloorService;
import com.zzyl.nursing.service.IRoomService;
import com.zzyl.nursing.service.IRoomTypeService;
import com.zzyl.nursing.vo.RoomVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Set;

/**
 * 房间Service业务层处理
 *
 * @author ruoyi
 * @date 2024-04-26
 */
@Service
public class RoomServiceImpl extends ServiceImpl<RoomMapper, Room> implements IRoomService {
    @Autowired
    private RoomMapper roomMapper;
    @Autowired
    private IFloorService floorService;
    @Autowired
    private IRoomTypeService roomTypeService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 查询房间
     *
     * @param id 房间主键
     * @return 房间
     */
    @Override
    public Room selectRoomById(Long id) {
        return getById(id);
    }

    /**
     * 查询房间列表
     *
     * @param room 房间
     * @return 房间
     */
    @Override
    public List<Room> selectRoomList(Room room) {
        return roomMapper.selectRoomList(room);
    }

    /**
     * 新增房间
     *
     * @param room 房间
     * @return 结果
     */
    @Override
    public int insertRoom(Room room) {
        return save(room) ? 1 : 0;
    }

    /**
     * 修改房间
     *
     * @param room 房间
     * @return 结果
     */
    @Override
    public int updateRoom(Room room) {
        clearCache();
        return updateById(room) ? 1 : 0;
    }

    /**
     * 批量删除房间
     *
     * @param ids 需要删除的房间主键
     * @return 结果
     */
    @Override
    public int deleteRoomByIds(Long[] ids) {
        clearCache();
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 根据楼层 id 获取房间视图对象列表
     *
     * @param floorId
     * @return
     */
    @Override
    public List<RoomVo> getRoomsByFloorId(Long floorId) {
        return roomMapper.selectByFloorId(floorId);
    }


    /**
     * 获取所有房间（负责老人）
     *
     * @param floorId
     * @return
     */
    @Override
    public List<RoomVo> getRoomsWithNurByFloorId(Long floorId) {
        return roomMapper.selectByFloorIdWithNur(floorId);
    }

    /**
     * 根据房间id查询房间数据(楼层、房间、价格)
     * 优化方法1：使用redis做缓存 使用hash类型
     *
     * @param id
     */
    @Override
    public RoomVo getRoomById(Long id) {
        //使用redis做优化
        //先查询redis缓存,查看是否有数据
        String o = String.valueOf(redisTemplate.opsForHash().get(CacheConstants.NURSING_ROOM_DETAIL, String.valueOf(id)));
        //判断缓存中是否有数据
        RoomVo roomVo = null;
        if (!StrUtil.isBlank(o)) {
            //不是空转化一下
            roomVo = JSON.parseObject(o, RoomVo.class);
        }

        if (roomVo == null) {
            // //需要查询数据库 ，查询房间数据
            Room one = this.getOne(Wrappers.<Room>lambdaQuery().eq(Room::getId, id));
            if (one == null) {
                throw new BaseException("房间不存在");
            }
            roomVo = new RoomVo();
            //根据房间id查询楼层信息
            Floor floor = floorService.getOne(Wrappers.<Floor>lambdaQuery().eq(Floor::getId, one.getFloorId()));
            if (floor == null) {
                throw new BaseException("楼层不存在");
            }
            roomVo.setFloorId(String.valueOf(floor.getId()));
            roomVo.setFloorName(floor.getName());
            roomVo.setRoomId(String.valueOf(one.getId()));
            roomVo.setCode(one.getCode());
            //查询房间价格
            RoomType roomType = roomTypeService.getOne(Wrappers.<RoomType>lambdaQuery()
                    .eq(RoomType::getName, one.getTypeName()));
            if (roomType != null) {
                roomVo.setPrice(String.valueOf(roomType.getPrice()));
            }
            //存储数据到redis中
            redisTemplate.opsForHash().put(CacheConstants.NURSING_ROOM_DETAIL, String.valueOf(id), JSON.toJSONString(roomVo));
        }
        return roomVo;
    }


//
//    /**
//     * 根据房间id查询房间数据(楼层、房间、价格)
//     *  优化方法2：使用redis做缓存 使用String类型  由于每一个床位都需要创建一个key，性能没有第一种方式好
//     * @param id
//     */
//    @Override
//    public RoomVo getRoomById(Long id) {
//        //使用redis做优化，首先先构建一个唯一的key
//        String key = CacheConstants.NURSING_ROOM_DETAIL + id;
//        //先查询redis缓存,查看是否有数据
//        String o = redisTemplate.opsForValue().get(key);
//        //判断缓存中是否有数据
//        RoomVo roomVo = null;
//        if (!StrUtil.isBlank(o)) {
//            //不是空转化一下
//            roomVo = JSON.parseObject(o, RoomVo.class);
//        }
//
//        if (roomVo == null) {
//            // //需要查询数据库 ，查询房间数据
//            Room one = this.getOne(Wrappers.<Room>lambdaQuery().eq(Room::getId, id));
//            if (one == null) {
//                throw new BaseException("房间不存在");
//            }
//            roomVo = new RoomVo();
//            //根据房间id查询楼层信息
//            Floor floor = floorService.getOne(Wrappers.<Floor>lambdaQuery().eq(Floor::getId, one.getFloorId()));
//            if (floor == null) {
//                throw new BaseException("楼层不存在");
//            }
//            roomVo.setFloorId(String.valueOf(floor.getId()));
//            roomVo.setFloorName(floor.getName());
//            roomVo.setRoomId(String.valueOf(one.getId()));
//            roomVo.setCode(one.getCode());
//            //查询房间价格
//            RoomType roomType = roomTypeService.getOne(Wrappers.<RoomType>lambdaQuery()
//                    .eq(RoomType::getName, one.getTypeName()));
//            if (roomType != null) {
//                roomVo.setPrice(String.valueOf(roomType.getPrice()));
//            }
//            //存储数据到redis中
//            redisTemplate.opsForValue().set(key, JSON.toJSONString(roomVo));
//        }
//        return roomVo;
//    }


    /**
     * 清除缓存
     */
    public void clearCache() {
        Set<String> keys = redisTemplate.keys(CacheConstants.NURSING_ROOM_DETAIL + "*");
        if (!CollectionUtils.isEmpty(keys)) {
            redisTemplate.delete(keys);
        }
    }
}